package sse.ustc.cc.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import sse.ustc.cc.util.CallOtherOpenFile;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public class FileLocalAty extends Activity {
	protected static final int GUI_STOP_NOTIFIER = 0x108;
	protected static final int GUI_THREADING_NOTIFIER = 0x109;

	private ListView lv;
	private ArrayList<File> list = new ArrayList<File>();
	private CallOtherOpenFile openfile;
	private ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	private RadioGroup sources = null;
	private RadioButton pdf = null;
	private RadioButton office = null;
	private RadioButton other = null;
	private int counter = 0;
	private ProgressDialog pd;
	protected Handler hander;
	private SimpleAdapter adapter;
	private Boolean threadbool = false;

	@SuppressLint({ "NewApi", "SdCardPath" })
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cc_file);
		this.sources = (RadioGroup) findViewById(R.id.sources);
		this.pdf = (RadioButton) findViewById(R.id.pdf);
		this.office = (RadioButton) findViewById(R.id.office);
		this.other = (RadioButton) findViewById(R.id.other);
		lv = (ListView) findViewById(R.id.listView1);
		openfile = new CallOtherOpenFile();
		list.clear();
		if (ExistSDCard()) {// sd exit
			// 获取所有sd卡的文件信息
			// 给RadioButton设置事件监听
			this.sources
					.setOnCheckedChangeListener(new OnCheckedChangeListenerImp());
			hander = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 0:
						getMapData(list).clear();
						adapter = new SimpleAdapter(FileLocalAty.this,
								getMapData(list), R.layout.cc_file_item,
								new String[] { "itemfileName" },
								new int[] { R.id.fileName });
						Log.e("adapter", "adapter");

						adapter.notifyDataSetChanged(); // 发送消息通知ListView更新
						lv.setAdapter(adapter); // 重新设置ListView的数据适配器
						break;
					default:
						// do something
						break;
					}
				}
			};

			// lv.setAdapter(adapter);
			setListViewHeightBasedOnChildren(lv);
			// final ListAdapter listAdapter = lv.getAdapter();

			// 单击列表，测试文件显示名称
			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// 测试文件显示名称
					Toast.makeText(FileLocalAty.this,
							"" + list.get(arg2).getName().toString(),
							Toast.LENGTH_LONG).show();
					openfile.openFile(getApplicationContext(), list.get(arg2));
					// openfile.openFile(getApplicationContext(), file)
					// File f = new File(list.get(arg2).getAbsolutePath());

				}
			});
			// 添加长按点击,得到点中的index，即参数arg2
			lv.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					File f = new File(list.get(arg2).getAbsolutePath());
					// 调用系统接口，获得手机上存在Aciton_send接口
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_SEND);
					intent.setType("*/*");
					intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
					startActivity(intent);
					return false;
				}
			});
		} else {
			Toast.makeText(getApplicationContext(), "您的手机尚未安装内存卡！",
					Toast.LENGTH_LONG).show();

		}
	}

	private class OnCheckedChangeListenerImp implements OnCheckedChangeListener {

		public void onCheckedChanged(RadioGroup group, int checkedId) {

			if (FileLocalAty.this.pdf.getId() == checkedId) {
				/* 显示ProgressDialog */
				pd = ProgressDialog.show(FileLocalAty.this.getParent(),
						"PDF资源", "加载中，请稍后……");
				// 开始动态加载线程
				//new Thread(runnableRemove).start();
				
			
					new Thread(runnablePdf).start();
				
				
			} else if (FileLocalAty.this.office.getId() == checkedId) {
				pd = ProgressDialog.show(FileLocalAty.this.getParent(),
						"OFFICE资源", "加载中，请稍后……");
				// 开始动态加载线程
				//new Thread(runnableRemove).start();
				new Thread(runnableOffice).start();
			} else if (FileLocalAty.this.other.getId() == checkedId) {
				pd = ProgressDialog.show(FileLocalAty.this.getParent(),
						"其它类型资源", "加载中，请稍后……");
				// 开始动态加载线程
				//new Thread(runnableRemove).start();
				new Thread(runnableOther).start();
			}else{
			}

		}
	}

	/**
	 * 加载PDF
	 */
	Runnable runnablePdf = new Runnable() {

		@Override
		public void run() {
			list.clear();
			getPdfFiles(new File("/sdcard")); // 加载PDF

			hander.sendEmptyMessage(0); // 下载完成后发送处理消息
			pd.dismiss(); // 关闭进度条对话框
		}
	};

	/**
	 * 加载OFFICE
	 */
	Runnable runnableOffice = new Runnable() {

		@Override
		public void run() {
			list.clear();
			getOfficeFiles(new File("/sdcard")); // 加载OFFICE

			hander.sendEmptyMessage(0); // 加载完成后发送处理消息
			pd.dismiss(); // 关闭进度条对话框
		}
	};

	/**
	 * 加载其他
	 */

	Runnable runnableOther = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			list.clear();
			getOtherFiles(new File("/sdcard")); // 加载其他

			hander.sendEmptyMessage(0); // 加载完成后发送处理消息
			pd.dismiss(); // 关闭进度条对话框
		}
	};

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 */
	private boolean ExistSDCard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * 动态调整item的高度
	 * 
	 * @param listView
	 */
	public void setListViewHeightBasedOnChildren(ListView listView) {

		ListAdapter listAdapter = listView.getAdapter();

		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		Log.e("listAdapter.getCount()", listAdapter.getCount() + "");
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();

		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));

		listView.setLayoutParams(params);
	}

	/**
	 * 填充到SimpleAdapter
	 * 
	 * @param 列表参数list
	 * @return ArrayList
	 * @exception 无
	 */
	private ArrayList<Map<String, Object>> getMapData(ArrayList<File> list) {
		HashMap<String, Object> item;
		int i = 0;
		for (i = 0; i < list.size(); i++) {
			item = new HashMap<String, Object>();
			String path = list.get(i).toString();
			String name = path.substring(path.lastIndexOf("/") + 1,
					path.length());
			item.put("itemfileName", name);
			data.add(item);
		}
		return data;
	}

	/**
	 * 获取sd卡文件
	 * 
	 * @param 参数file是文件名
	 * @return 无
	 * @exception 无
	 */
	private void getPdfFiles(File file) {

		File files[] = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {// 如果是文件夹的话，递归调用
					getPdfFiles(f);// 循环显示
				} else {// 如果是文件的话，筛选pdf和ppt的文件，添加到列表中
					String fileName = f.getName();

					if (fileName.endsWith(".pdf")) {

						this.list.add(f);
					}
				}
			}
		}
	}

	private void getOfficeFiles(File file) {

		File files[] = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {// 如果是文件夹的话，递归调用
					getOfficeFiles(f);// 循环显示
				} else {// 如果是文件的话，筛选pdf和ppt的文件，添加到列表中
					String fileName = f.getName();

					if (fileName.endsWith(".xls") || fileName.endsWith(".doc")
							|| fileName.endsWith(".ppt")) {

						this.list.add(f);
					}
				}
			}
		}
	}

	private void getOtherFiles(File file) {

		File files[] = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {// 如果是文件夹的话，递归调用
					getOtherFiles(f);// 循环显示
				} else {
					String fileName = f.getName();

					if (fileName.endsWith(".txt")
							|| fileName.endsWith(".apk")) {

						this.list.add(f);
					}
				}
			}
		}
	}

}
